package cn.js189.uqc.task;

import cn.js189.common.util.helper.UUIDHelper;
import cn.js189.uqc.common.WxService;
import cn.js189.uqc.domain.invoice.InvoiceAuthDTO;
import cn.js189.uqc.mapper.CheckInfoMapper;
import cn.js189.uqc.redis.RedisOperation;
import cn.js189.uqc.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 公众号领取发票授权定时任务
 */
public class WxAuthTask implements Runnable{

	private static final Logger LOGGER = LoggerFactory.getLogger(WxAuthTask.class);

	private WxService wxService;

	private CheckInfoMapper checkInfoMapper;

	private RedisOperation redisOperation;

	private static final String WX_CARD_AUTH_PREIFX = "CARD_AUTH_";

	public WxAuthTask(WxService wxService, CheckInfoMapper checkInfoMapper,RedisOperation redisOperation) {
		this.wxService = wxService;
		this.checkInfoMapper = checkInfoMapper;
		this.redisOperation = redisOperation;
	}

	@Override
	public void run() {
		LOGGER.info("微信查询授权状态定时任务启动...");
		List<InvoiceAuthDTO> invoiceInfos = this.checkInfoMapper.selectInvoiceAuthStatus();
		if (null != invoiceInfos && !invoiceInfos.isEmpty()) {
			LOGGER.info("微信查询授权状态定时任务查询出数据:{}", invoiceInfos.size());
			
			for (InvoiceAuthDTO invoiceAuthDTO : invoiceInfos) {
				String invoiceId = invoiceAuthDTO.getInvoiceId();
				String type = invoiceAuthDTO.getType();
				String ticketId = invoiceAuthDTO.getTicketId();
				String lockValue = UUIDHelper.getUUID();
				String lockKey = WX_CARD_AUTH_PREIFX + invoiceId;
				try {
					String lockResult = RedisUtil.tryLock(redisOperation, "电子发票查询授权", lockKey, lockValue);
					// 获取锁失败
					if (!StringUtils.equals(lockResult, RedisUtil.LOCK_SUCCESS)) {
						continue;
					}
					this.wxService.checkTicketAuthInfo(ticketId, invoiceId, type);
				} catch (Exception e) {
					LOGGER.info("发票【{}】插卡任务异常 {}", invoiceId, e.getMessage());
				}
				RedisUtil.unlock(redisOperation, "电子发票查询授权", lockKey, lockValue);
			}
		}
	}
}
